package com.shuyuansystem.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.shuyuansystem.dao.OrderInfoMapper;
import com.shuyuansystem.entity.AliPayConfig;
import com.shuyuansystem.pojo.AliPay;
import com.shuyuansystem.pojo.OrderInfo;
import com.shuyuansystem.pojo.OrderList;
import com.shuyuansystem.pojo.User;
import com.shuyuansystem.service.OrderInfoService;
import com.shuyuansystem.service.OrderListService;
import com.shuyuansystem.utils.JWTUtils;
import com.shuyuansystem.dao.CheckRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/OrderHistory")
public class OrderHistoryController {
    @Resource
    private AliPayConfig aliPayConfig;

    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private CheckRoleMapper checkRoleMapper;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private OrderListService orderListService;

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";
    // 导入 User 类，便于接收前端的角色数据
    User user = new User();

    @GetMapping("/getRoleAndUserId")
    public User getRoleAndUserId(@RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 去除 Bearer 前缀
            token = token.replace("Bearer ", "");
            // 从 Token 中获取用户 ID
            String userId = JWTUtils.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无法从 Token 中获取用户 ID");
                return null;
            }
            // 根据用户 ID 查询角色
            String role = checkRoleMapper.checkRoleById(userId);
            if (role == null) {
                response.put("success", false);
                response.put("message", "未找到该用户的角色信息");
                return null;
            }

            user.setId(Integer.parseInt(userId));
            user.setRole(role);
            response.put("userId", userId);
            response.put("role", role);
            response.put("success", true);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理请求时发生错误: " + e.getMessage());
        }
        return user;
    }

    @GetMapping("/OrderHistory")
    public List<Map<String, Object>> OrderHistory(@RequestParam("userId") String userId) {
        // 根据指定的用户 ID 获取订单信息
        List<OrderInfo> orderInfos = orderInfoService.getAllByUserId(userId);

        // 提取所有商家订单号码
        List<String> merchantOrderNumbers = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            if (orderInfo.getMerchantOrderNumber() != null) {
                merchantOrderNumbers.add(orderInfo.getMerchantOrderNumber());
            }
        }

        // 根据商家订单号码查询对应的订单列表信息
        List<OrderList> orderLists = orderListService.getByMerchantOrderNumbers(merchantOrderNumbers);
        // 整合信息
        Map<String, List<OrderList>> integratedMap = new HashMap<>();
        for (OrderList orderList : orderLists) {
            String merchantOrderNumber = orderList.getMerchant_order_number();
            integratedMap.computeIfAbsent(merchantOrderNumber, k -> new ArrayList<>()).add(orderList);
        }

        // 构建最终返回的结果列表
        List<Map<String, Object>> result = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            String merchantOrderNumber = orderInfo.getMerchantOrderNumber();
            Map<String, Object> orderData = new HashMap<>();
            orderData.put("userId", orderInfo.getUserId());
            orderData.put("merchantId", orderInfo.getMerchantId());
            orderData.put("shippingAddress", orderInfo.getShippingAddress());
            orderData.put("receiverPhone", orderInfo.getReceiverPhone());
            orderData.put("remark", orderInfo.getRemark());
            orderData.put("totalPrice", orderInfo.getTotalPrice());
            // 直接放入 transactionStatus
            orderData.put("transactionStatus", orderInfo.getTransactionStatus());
            // 直接放入 orderStatus
            orderData.put("orderStatus", orderInfo.getOrderStatus());
            orderData.put("merchantOrderNumber", merchantOrderNumber);
            orderData.put("videoUrl", orderInfo.getVideoUrl());

            List<OrderList> relatedOrderLists = integratedMap.get(merchantOrderNumber);
            if (relatedOrderLists != null) {
                orderData.put("orderDetails", relatedOrderLists);
            }
            result.add(orderData);
        }
        return result;
    }
    @PostMapping("/payOrder")
    public void payOrder(@RequestParam("orderNumber") String orderNumber, @RequestParam("userId") String userId, @RequestParam("merchantId") String merchantId, HttpServletResponse response) throws IOException {
        System.out.println("收到支付请求，订单号: " + orderNumber + "，用户 ID: " + userId + "，商家 ID: " + merchantId);

        // 根据订单号获取订单信息
        OrderInfo orderInfo = orderInfoMapper.getOrderInfoByMerchantOrderNumber(orderNumber);
        if (orderInfo == null || "订单已支付".equals(orderInfo.getOrderStatus())) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("订单不存在或已支付！");
            response.getWriter().flush();
            response.getWriter().close();
            return;
        }

        // 构建支付请求参数
        AliPay aliPay = new AliPay();
        aliPay.setTraceNo(orderNumber);
        aliPay.setTotalAmount(orderInfo.getTotalPrice().doubleValue());
        aliPay.setSubject("商品支付");

        try {
            // 生成支付表单
            String form = generateAlipayForm(aliPay);

            // 将支付表单返回给客户端
            response.setContentType("text/html;charset=" + CHARSET);
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("支付请求失败，请稍后重试！");
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    private String generateAlipayForm(AliPay aliPay) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        return alipayClient.pageExecute(request).getBody();
    }


    // 取消订单方法
    @PostMapping("/cancelOrder")
    public void cancelOrder(@RequestParam("orderNumber") String orderNumber, @RequestParam("userId") String userId, @RequestParam("merchantId") String merchantId) {
        orderInfoService.cancelOrder(orderNumber);
        orderListService.cancelOrderList(orderNumber);
        System.out.println("收到取消订单请求，订单号: " + orderNumber + "，用户 ID: " + userId + "，商家 ID: " + merchantId);
    }
    // 申请退款接口
    @PostMapping("/refundOrder")
    public void refundOrder(@RequestParam("orderNumber") String orderNumber,
                            @RequestParam("userId") String userId,
                            @RequestParam("merchantId") String merchantId,
                            HttpServletResponse response) throws IOException {
        System.out.println("收到退款请求，订单号: " + orderNumber + "，用户 ID: " + userId + "，商家 ID: " + merchantId);

        // 根据订单号获取订单信息
        OrderInfo orderInfo = orderInfoMapper.getOrderInfoByMerchantOrderNumber(orderNumber);
        if (orderInfo == null || !"订单已支付".equals(orderInfo.getOrderStatus())) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("该订单不存在或未支付，无法退款！");
            response.getWriter().flush();
            response.getWriter().close();
            return;
        }

        double refundAmount = orderInfo.getTotalPrice().doubleValue();

        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{\"out_trade_no\":\"" + orderNumber + "\","
                + "\"refund_amount\":\"" + refundAmount + "\"}");

        try {
            AlipayTradeRefundResponse alipayResponse = alipayClient.execute(request);
            if (alipayResponse.isSuccess()) {
                // 退款成功，更新数据库订单状态
                OrderInfo updateOrder = new OrderInfo();
                updateOrder.setMerchantOrderNumber(orderNumber);
                updateOrder.setOrderStatus("订单已退款");
                orderInfoMapper.updateOrderStatus(updateOrder);

                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("退款成功！");
            } else {
                // 退款失败
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("退款失败，错误码: " + alipayResponse.getCode() + "，错误信息: " + alipayResponse.getMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("退款请求出错，请稍后重试！");
        } finally {
            response.getWriter().flush();
            response.getWriter().close();
        }
    }
}